package com.ys.service.storage.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ys.dto.AddDto;
import com.ys.dto.EditDto;
import com.ys.entity.business.TpAmazonShop;
import com.ys.entity.business.TpAmazonShopProduct;
import com.ys.entity.business.TpProductActive;
import com.ys.entity.finance.TcwAccountCountForCompany;
import com.ys.entity.flow.YspModel;
import com.ys.entity.hr.ThrOperateCompanyApply;
import com.ys.entity.storage.*;
import com.ys.entity.sys.TsUserChange;
import com.ys.entity.sys.YsMenu;
import com.ys.entity.sys.YsProcInst;
import com.ys.enume.finance.TcwOperateFrozenRunningEnum;
import com.ys.enume.flow.FlowEnum;
import com.ys.enume.flow.YsProcInstEnum;
import com.ys.enume.storage.*;
import com.ys.mapper.storage.TccFbaFeeDetailsMapper;
import com.ys.mapper.storage.TccFbaLogisticsMethodMapper;
import com.ys.mapper.storage.TccFbaPlanItemMapper;
import com.ys.mapper.storage.TccFbaPlanMapper;
import com.ys.service.finance.TcwAccountCountForCompanyService;
import com.ys.service.flow.YspTaskService;
import com.ys.service.storage.*;
import com.ys.util.FbaUtils;
import com.ys.util.shiro.BeanUtils;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.Flow;
import com.ys.vo.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: fxz
 * @CreateTime: 2024-12-04
 * @Description: FBA计划单实现层
 * @Version: 1.5
 */
@Service("tccFbaFeeDetailsService")
public class TccFbaFeeDetailsServiceImpl implements TccFbaFeeDetailsService {
    private static final Logger logger = LoggerFactory.getLogger(TccFbaFeeDetailsServiceImpl.class);

    @Autowired
    private TccStockControlService tccStockControlService;

    @Autowired
    private TccFbaPlanMapper tccFbaPlanMapper;

    @Autowired
    private TccFbaPlanItemMapper tccFbaPlanItemMapper;

    @Autowired
    private TccFbaLogisticsMethodMapper tccFbaLogisticsMethodMapper;

    @Autowired
    private YspTaskService yspTaskService;

    @Autowired
    private TccFbaFeeDetailsMapper tccFbaFeeDetailsMapper;

    @Autowired
    private TcwAccountCountForCompanyService tcwAccountCountForCompanyService;

    @Autowired
    private FbaInboundApiService fbaInboundApiService;

    @Autowired
    private TccFbaBoxUpService tccFbaBoxUpService;

    /**
     * 新增
     */
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public R add(Map<String, Object> params, Long menuId) throws Exception {
        //判断网店-物流方式不允许为空
        if (params.get("shopId") == null){
            return R.error("网店名称不允许为空!");
        }
        if (params.get("logsticsWayId") == null){
            return R.error("物流方式不允许为空!");
        }
        TccFbaPlan entity = JSON.parseObject(JSON.toJSONString(params),TccFbaPlan.class);
        entity.setStatus(TccFbaPlanEnum.Status.EMPTY.value);//状态
        entity.setEffectStock(0);//审批状态

        //获取制单人信息
        TsUserChange tsUserChange = new TsUserChange().setUserId(ShiroUtils.getUserId()).setStatus(1).queryFirst();
        if(tsUserChange!=null){
            entity.setCreateChangeId(tsUserChange.getId());//制单人变更信息
        }else {
            return R.error("未查询到制单人信息！");
        }
        tccFbaPlanMapper.insert(entity);

        R r = pdParams(params, entity);
        if (r.getCode() != 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return R.error(r.getMsg());
        }
        YsMenu ysMenu = new YsMenu().setId(menuId).queryFirst();
        if (ysMenu.getFlowModelId().longValue() != 0L) {
            YspModel yspModel = new YspModel().setId(ysMenu.getFlowModelId()).queryFirst();
            String codeModel = yspModel.getCode();
            String createUserId = ShiroUtils.getUserId();
            yspTaskService.init(codeModel, entity.getBid(), createUserId);
        }

        return R.ok(AddDto.gotoEdit("/web/storage/tccFbaPlan/toEdit?bid=" + entity.getBid()));
    }


    /**
     * 修改fba计划单
     * @param params
     * @param menuId
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public R toEdit(Map<String, Object> params, Long menuId) throws Exception {
        //判断网店-物流方式不允许为空
        if (params.get("shopId") == null){
            return R.error("网店名称不允许为空!");
        }
        if (params.get("logsticsWayId") == null){
            return R.error("物流方式不允许为空!");
        }
        TccFbaPlan entity = JSON.parseObject(JSON.toJSONString(params),TccFbaPlan.class);
        TccFbaPlan tccFbaPlan = new TccFbaPlan().setBid(entity.getBid()).queryFirst();
        if (tccFbaPlan == null){
            return R.error("FBA计划单不存在,请核实后再操作!");
        }

        tccFbaPlanMapper.update(entity);

        //删除子表数据..并且解冻库存
        R r1 = delItem( entity);
        if (r1.getCode() != 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return R.error(r1.getMsg());
        }

        R r = pdParams(params, entity);
        if (r.getCode() != 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return R.error(r.getMsg());
        }
        return R.ok(AddDto.gotoEdit("/web/storage/tccFbaPlan/toEdit?bid=" + entity.getBid()));
    }




    /**
     * 删除子表数据..并且解冻库存
     */
    private R delItem(TccFbaPlan entity){
        try {
            List<TccFbaPlanItem> tccFbaPlanItemList = new TccFbaPlanItem().setBidFbaPlan(entity.getBid()).queryList();
            for (TccFbaPlanItem tccFbaPlanItem : tccFbaPlanItemList){
                //解冻流水
                tccStockControlService.thaw(
                        tccFbaPlanItem.getStockControlId(),
                        tccFbaPlanItem.getNumPlanDeliver(),
                        TccStockFrozenRunningEnum.SourceType.TCC_FBAPLAN_FINISH.value,
                        entity.getBid(),
                        entity.getId());
                tccFbaPlanItemMapper.deleteTrue(tccFbaPlanItem.getId());
            }
            TccFbaFeeDetails tccFbaFeeDetails = new TccFbaFeeDetails().setSourceBid(entity.getBid()).setSourceType(TccFbaLogisticsMethodEnum.SourceType.FBAPLAN.value).queryFirst();
            if (tccFbaFeeDetails.getPriceTranPredict().compareTo(BigDecimal.ZERO) != 0){
                //冻结资金
                tcwAccountCountForCompanyService.thaw(
                        entity.getVgsbm(),
                        tccFbaFeeDetails.getPriceTranPredict(),
                        TcwOperateFrozenRunningEnum.DocumentType.TCC_FbaPlan.value,
                        tccFbaFeeDetails.getId(),
                        entity.getBid(),
                        entity.getBid()
                );
            }
            tccFbaFeeDetailsMapper.deleteTrue(tccFbaFeeDetails.getId());

            TccFbaLogisticsMethod tccFbaLogisticsMethod = new TccFbaLogisticsMethod().setSourceBid(entity.getBid()).setSourceType(TccFbaLogisticsMethodEnum.SourceType.FBAPLAN.value).queryFirst();
            tccFbaLogisticsMethodMapper.deleteTrue(tccFbaLogisticsMethod.getId());

        } catch (Exception e) {
            return R.error(e.getMessage());
        }
        return R.ok();
    }

    /**
     * 判断参数
     * @return
     */
    private R pdParams(Map<String, Object> params,TccFbaPlan entity){
        try {

            TccLogisticsMethod tccLogisticsMethod = new TccLogisticsMethod().setId(Long.valueOf(params.get("logsticsWayId").toString())).queryFirst();

            TpAmazonShop tpAmazonShop = new TpAmazonShop().setId(entity.getShopId()).queryFirst();
            if (tpAmazonShop.getPhone() == null || tpAmazonShop.getPhone().equals("")) {
                return R.error("Amazon店铺管理电话未维护!");
            }
            if (tpAmazonShop.getName() == null || tpAmazonShop.getAddressLine1() == null || tpAmazonShop.getCity() == null ||
                    tpAmazonShop.getStateOrProvinceCode() == null || tpAmazonShop.getPostalCode() == null
                    || tpAmazonShop.getName().equals("") || tpAmazonShop.getAddressLine1().equals("") || tpAmazonShop.getCity().equals("")
                    || tpAmazonShop.getStateOrProvinceCode().equals("") || tpAmazonShop.getPostalCode().equals("")) {
                return R.error("Amazon店铺管理发货地址未维护!");
            }
            //根据店铺是否欧代标判断 （打印欧盟标使用）
            if (tpAmazonShop.getEuStatus() == 1) {
                if (tpAmazonShop.getEuAgent() == null || tpAmazonShop.getEuAgentAddress() == null || tpAmazonShop.getManufacturer() == null ||
                        tpAmazonShop.getManufacturerAddress() == null
                        || tpAmazonShop.getEuAgent().equals("") || tpAmazonShop.getEuAgentAddress().equals("") || tpAmazonShop.getManufacturer().equals("")
                        || tpAmazonShop.getManufacturerAddress().equals("")) {
                    return R.error("Amazon店铺管理欧盟信息未维护!");
                }
            }

            //运输类型维护
            TccTransportationType tccTransportationType = new TccTransportationType().setId(tccLogisticsMethod.getTransportationId()).queryFirst();
            if (entity.getDeliverState() == 1 && entity.getCreationMethod() == 1){
                //按SKU自动发货不允许LTL以外的发货方式
                if (!tccTransportationType.getTransportationTypeEn().equals("FREIGHT_LTL")){
                    return R.error("下单方式:自动,发货计划:按SKU自动发货,运输类型只允许LTL方式");
                }
            }


            //查询运营公司备案
            ThrOperateCompanyApply drOperateCompanyApply = new ThrOperateCompanyApply().setVgsbm(entity.getVgsbm()).queryFirst();
            if (drOperateCompanyApply.getVgsSh() == null || drOperateCompanyApply.getVgsSh().equals("")) {
                throw new RuntimeException("公司名称和税号不能为空，请维护!");
            }


            //查询仓库信息
            TccWarehouse tccWarehouse = new TccWarehouse().setCck(tccLogisticsMethod.getCck()).queryFirst();

            //计重梯度+抛重梯度
            List<TccLogisticsMethodItem> tccLogisticsMethodItemList = new TccLogisticsMethodItem()
                    .setMethodId(tccLogisticsMethod.getId())
                    .queryList();
            //计重梯度
            List<TccLogisticsMethodItem> jzTdList  = tccLogisticsMethodItemList.stream().filter(tccLogisticsMethodItem ->
                    TccLogisticsMethodItemEnum.LogisticsMethodType.JZTD.value.equals(tccLogisticsMethodItem.getLogisticsMethodType())).collect(Collectors.toList());
            //抛重梯度
            List<TccLogisticsMethodItem> pzTdList  = tccLogisticsMethodItemList.stream().filter(tccLogisticsMethodItem ->
                    TccLogisticsMethodItemEnum.LogisticsMethodType.PZTD.value.equals(tccLogisticsMethodItem.getLogisticsMethodType())).collect(Collectors.toList());

            List<TccLogisticsMethodItemSon> czTdList = new TccLogisticsMethodItemSon()
                    .setMethodId(tccLogisticsMethod.getId())
                    .queryList();

            //报关
            HashSet<Integer> declarationStateList = new HashSet<Integer>();
            //品名数量
            Set<String> gradeNum = new HashSet<>();
            //SKU
            Set<String> skuList = new HashSet<>();
            //仓库SKU是否统一
            Map<String, Object> chwSkuList = new HashMap<>();
            //实重（kg）
            BigDecimal weightReal = BigDecimal.ZERO;
            //抛重（kg）
            BigDecimal weightVol = BigDecimal.ZERO;
            //计重（kg）
            BigDecimal weightCal = BigDecimal.ZERO;

            //计重梯度
            BigDecimal jfStart = BigDecimal.ZERO;
            BigDecimal jfEnd = BigDecimal.ZERO;
            BigDecimal jfFee = BigDecimal.ZERO;

            //抛重梯度
            BigDecimal pzStart = BigDecimal.ZERO;
            BigDecimal pzEnd = BigDecimal.ZERO;
            BigDecimal pzFee = BigDecimal.ZERO;

            List<TccLogisticsMethodItem> tdjzPrice;

            List<TccLogisticsMethodItem> tdPzPrice;
            //超出品名数量
            Integer exceedNum = 0;
            //材质费用
            BigDecimal czFee = BigDecimal.ZERO;
            String czCn = "";
            String czEn = "";

            //保存列表信息
            if (params.get("subData") != null) {
                JSONArray subData = JSON.parseArray(params.get("subData").toString());
                if (subData.size() == 0){
                    return R.error("FBA计划单子表数据不允许为空!");
                }
                for (int i = 0; i < subData.size(); i++) {
                    JSONObject jSONObject = subData.getJSONObject(i);
                    TccFbaPlanItem tccFbaPlanItem = JSON.parseObject(JSON.toJSONString(jSONObject), TccFbaPlanItem.class);
                    if (jSONObject.get("numPlanDeliver") == null || jSONObject.getInteger("numPlanDeliver") == 0) {
                        return R.error("计划发货数量不允许为0或者为空！");
                    }
                    if (jSONObject.get("sku") == null) {
                        return R.error("SKU不允许为空！");
                    }
                    TpAmazonShopProduct tpAmazonShopProduct = new TpAmazonShopProduct().setShopId(entity.getShopId()).setSellerSku(jSONObject.get("sku").toString()).queryFirst();
                    if (tpAmazonShopProduct.getMainImage() == null || tpAmazonShopProduct.getFnSku() == null || tpAmazonShopProduct.getPackageLength() == null
                            || tpAmazonShopProduct.getPackageWidth() == null || tpAmazonShopProduct.getPackageHeight() == null) {
                        return R.error("请至Amazon商品管理，重新获取商品信息");
                    }
                    TpProductActive tpProductActive = new TpProductActive().setCode(jSONObject.get("commodityCode").toString()).queryFirst();
                    if (tpProductActive.getCommodityPlId() == null || tpProductActive.getCodeHs() == null || tpProductActive.getNameUnitId() == null
                            || tpProductActive.getNameId() == null || tpProductActive.getUsageId() == null || tpProductActive.getMaterialId() == null
                            || tpProductActive.getLinkIn() == null) {
                        return R.error("请至Listing库，完整维护商品物流发票信息");
                    }
                    if (jSONObject.get("priceIn") == null) {
                        return R.error("该库存缺少采购价,请联系客服人员修改后再操作!");
                    }
                    tccFbaPlanItem.setImg(tpProductActive.getImg());
                    declarationStateList.add(tccFbaPlanItem.getDeclarationItemState());
                    //不一样的品名数=(商品中文、海关编码、材质中文只要一个不同)
                    String join = tccFbaPlanItem.getNameGoodsCn() + '-' + tccFbaPlanItem.getCodeGoodsHs() + '-' + tccFbaPlanItem.getNameMaterialCn();
                    gradeNum.add(join);
                    skuList.add(tccFbaPlanItem.getSku());

                    //不一样的仓库库存=(SKU、ASIN、FNSKU、仓库只要一个不同)
                    String chwSku = tccFbaPlanItem.getSku() + '-' + tccFbaPlanItem.getAsin() + '-' + tccFbaPlanItem.getFnSku();
                    if (chwSkuList.get(chwSku) != null ){
                        if (!chwSkuList.get(chwSku).equals(tccFbaPlanItem.getChw())){
                            return R.error("该SKU:"+tccFbaPlanItem.getSku()+"不允许多个仓库,请处理后再操作!");
                        }
                    }
                    chwSkuList.put(chwSku,tccFbaPlanItem.getChw());
                    //判断是否是混合材质
                    if (tccFbaPlanItem.getNameMaterialCn().indexOf(",") == -1) {
                        //赋值材质附加费(取最大值)
                        for (int j = 0; j < czTdList.size(); j++) {
                            if (czTdList.get(j).getMaterialNameCn().equals(tccFbaPlanItem.getNameMaterialCn())) {
                                if (czTdList.get(j).getAdditionalMaterialBilling().compareTo(czFee) > 0) {
                                    czFee = (czTdList.get(j).getAdditionalMaterialBilling());
                                    czCn = (czTdList.get(j).getMaterialNameCn());
                                    czEn = (czTdList.get(j).getMaterialNameEn());
                                }
                            }
                        }
                    } else {
                        String[] nameMaterialCnList = tccFbaPlanItem.getNameMaterialCn().split(",");
                        for (String nameMaterialCn : nameMaterialCnList){
                            for (int j = 0; j < czTdList.size(); j++) {
                                if (czTdList.get(j).getMaterialNameCn().equals(nameMaterialCn)) {
                                    if (czTdList.get(j).getAdditionalMaterialBilling().compareTo(czFee) > 0) {
                                        czFee = (czTdList.get(j).getAdditionalMaterialBilling());
                                        czCn = (czTdList.get(j).getMaterialNameCn());
                                        czEn = (czTdList.get(j).getMaterialNameEn());
                                    }
                                }
                            }
                        }
                    }
                    //冻结流水
                    tccStockControlService.frozen(
                            tccFbaPlanItem.getStockControlId(),
                            tccFbaPlanItem.getNumPlanDeliver(),
                            TccStockFrozenRunningEnum.SourceType.TCC_FBAPLAN_PASS.value,
                            entity.getBid(),
                            entity.getId());

                    //（商品重量*计划发货数量）之和
                    weightReal = weightReal.add((tccFbaPlanItem.getWeightPackage().multiply(new BigDecimal(tccFbaPlanItem.getNumPlanDeliver()))).setScale(2, RoundingMode.HALF_UP));
                    //（商品包装尺寸相乘*计划发货数量/抛货系数）之和
                    weightVol = weightVol.add((tccFbaPlanItem.getLengthPackage().multiply(tccFbaPlanItem.getWidthPackage()).multiply(tccFbaPlanItem.getHeightPackage()).multiply(new BigDecimal(tccFbaPlanItem.getNumPlanDeliver())))
                            .divide(new BigDecimal(tccLogisticsMethod.getCoefficientWeight()), 2, RoundingMode.HALF_UP));
                    tccFbaPlanItem.setBidFbaPlan(entity.getBid());
                    tccFbaPlanItemMapper.insert(tccFbaPlanItem);
                }
                if (declarationStateList.size() > 1) {
                    return R.error("非报关商品和报关商品不能下同一个FBA计划!");
                }
                if (gradeNum.size() > tccLogisticsMethod.getMaxProNameNum()) {
                    return R.error("实际品名数量:" + gradeNum.size() + ",大于品名上限数量:" + tccLogisticsMethod.getMaxProNameNum());
                }
                if (skuList.size() > 25) {
                    return R.error("SKU一次性不能超过25个!");
                }
                //MAX（实重,抛重）
                weightCal = weightReal.max(weightVol);
                //约分规则
                if (tccLogisticsMethod.getDivisionalRule() == TccLogisticsMethodEnum.DivisionalRule.INTO1.value){
                    weightCal = new BigDecimal(Math.ceil(weightCal.doubleValue()));
                }else if (tccLogisticsMethod.getDivisionalRule() == TccLogisticsMethodEnum.DivisionalRule.INTO_05_1.value){
                    weightCal = FbaUtils.precision(weightCal);
                }
                //MAX【单票起重（kg），单票起重（kg）】
                weightCal = weightCal.max(tccLogisticsMethod.getSinglePassCrane());
                weightCal = weightCal.max(tccLogisticsMethod.getWeightCalBySingle());

                //计重梯度价（￥/kg） 参照“计重”对应范围的梯度价
                BigDecimal finalWeightCal = weightCal;
                tdjzPrice = jzTdList.stream().filter(tccLogisticsMethodItem -> finalWeightCal.compareTo(tccLogisticsMethodItem.getHeavySn()) >= 0
                        && finalWeightCal.compareTo(tccLogisticsMethodItem.getHeavyEn()) <= 0).collect(Collectors.toList());

                //计重
                if (tdjzPrice.size() != 0){
                    jfStart = tdjzPrice.get(0).getHeavySn();
                    jfEnd =tdjzPrice.get(0).getHeavyEn();
                    jfFee = tdjzPrice.get(0).getPrice();
                }

                //抛重附加费（￥/kg） 参照“抛重-实重”对应范围的梯度价
                BigDecimal finalWeightVol = weightVol;
                tdPzPrice = pzTdList.stream().filter(tccLogisticsMethodItem -> finalWeightVol.compareTo(tccLogisticsMethodItem.getHeavySn()) >= 0
                        && finalWeightVol.compareTo(tccLogisticsMethodItem.getHeavyEn()) <= 0).collect(Collectors.toList());
                //抛重
                if (tdPzPrice.size() != 0){
                    pzStart = tdPzPrice.get(0).getHeavySn();
                    pzEnd =tdPzPrice.get(0).getHeavyEn();
                    pzFee = tdPzPrice.get(0).getPrice();
                }
            } else {
                return R.error("列表信息为空！");
            }



            //新增FBA物流维护
            TccFbaLogisticsMethod tccFbaLogisticsMethod = new TccFbaLogisticsMethod();
            BeanUtils.copyProperties(tccLogisticsMethod,tccFbaLogisticsMethod);
            tccFbaLogisticsMethod.setId(null);
            tccFbaLogisticsMethod.setLogsticsWayId(tccLogisticsMethod.getId());
            tccFbaLogisticsMethod.setSourceType(TccFbaLogisticsMethodEnum.SourceType.FBAPLAN.value);
            tccFbaLogisticsMethod.setSourceBid(entity.getBid());
            tccFbaLogisticsMethod.setTransportationCn(tccTransportationType.getTransportationTypeCn());
            tccFbaLogisticsMethod.setTransportationEn(tccTransportationType.getTransportationTypeEn());
            tccFbaLogisticsMethod.setVck(tccWarehouse.getVck());
            //计重
            tccFbaLogisticsMethod.setJfStart(jfStart);
            tccFbaLogisticsMethod.setJfEnd(jfEnd);
            tccFbaLogisticsMethod.setJfFee(jfFee);

            //抛重
            tccFbaLogisticsMethod.setPzStart(pzStart);
            tccFbaLogisticsMethod.setPzEnd(pzEnd);
            tccFbaLogisticsMethod.setPzFee(pzFee);

            //材质
            tccFbaLogisticsMethod.setCzFee(czFee);
            tccFbaLogisticsMethod.setCzCn(czCn);
            tccFbaLogisticsMethod.setCzEn(czEn);
            tccFbaLogisticsMethodMapper.insert(tccFbaLogisticsMethod);

            TccFbaFeeDetails tccFbaFeeDetails = new TccFbaFeeDetails();
            tccFbaFeeDetails.setWeightReal(weightReal);
            tccFbaFeeDetails.setWeightVol(weightVol);
            tccFbaFeeDetails.setWeightCal(weightCal);
            //计重*（计重梯度价+抛重附加费）
            tccFbaFeeDetails.setPriceTranCalWeight(tccFbaLogisticsMethod.getJfFee().add(tccFbaLogisticsMethod.getPzFee()));
            tccFbaFeeDetails.setNumProName(gradeNum.size());
            //（品名数量-免费品名数量）+负数取0】* 品名附加计费标准（￥/个)
            exceedNum = gradeNum.size()-tccFbaLogisticsMethod.getFreeProNameNum();
            tccFbaFeeDetails.setPriceProNameExtraPredict(exceedNum>0?
                    (new BigDecimal(exceedNum).multiply(tccFbaLogisticsMethod.getAdditionalStandardAmount())).setScale(2, BigDecimal.ROUND_HALF_UP)
                    :BigDecimal.ZERO);
            tccFbaFeeDetails.setPriceQualityExtra(czCn);
            //计重*材质附加计费（￥/kg）
            tccFbaFeeDetails.setPriceQualityExtraPredict((czFee.multiply(weightCal)).setScale(2, BigDecimal.ROUND_HALF_UP));
            //预估品名附加费（￥）+预估材质附加费（￥）+清关服务费(￥)
            tccFbaFeeDetails.setPriceExtraPredict(tccFbaFeeDetails.getPriceProNameExtraPredict().add(
                    tccFbaFeeDetails.getPriceQualityExtraPredict().add(tccFbaLogisticsMethod.getClearanceOpeAmount())
            ));
            tccFbaFeeDetails.setSourceType(TccFbaFeeDetailsEnum.SourceType.PLAN.value);
            tccFbaFeeDetails.setSourceBid(entity.getBid());
            //预估计重费（￥）+预估附加费（￥）
            tccFbaFeeDetails.setPriceTranPredict(tccFbaFeeDetails.getPriceTranCalWeight().add(tccFbaFeeDetails.getPriceExtraPredict()));
            tccFbaFeeDetails.setStatus(1);
            tccFbaFeeDetailsMapper.insert(tccFbaFeeDetails);

            //账户资金+负载额度+5000< 预估物流费用
            TcwAccountCountForCompany accountCountForCompany = new TcwAccountCountForCompany().setVGsBm(entity.getVgsbm()).queryFirst();
            if (accountCountForCompany.getFJe().add(accountCountForCompany.getFFzEd()).add(new BigDecimal(5000)).compareTo(tccFbaFeeDetails.getPriceTranPredict()) == -1){
                return R.error("资金不足,请核实后再操作!");
            }
            if (tccFbaFeeDetails.getPriceTranPredict().compareTo(BigDecimal.ZERO) != 0){
                //冻结资金
                tcwAccountCountForCompanyService.frozen(
                        entity.getVgsbm(),
                        tccFbaFeeDetails.getPriceTranPredict(),
                        TcwOperateFrozenRunningEnum.DocumentType.TCC_FbaPlan.value,
                        tccFbaFeeDetails.getId(),
                        entity.getBid(),
                        entity.getBid()
                );
            }

        } catch (Exception e) {
            return R.error(e.getMessage());
        }
        return R.ok();
    }


}
